#include "prologmath.h"

int mathfunc(QString name, variable* oper1,variable* result)
{
	if(name.compare(QString("ln"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = log(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
	}
	else if(name.compare(QString("log"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = log10(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
	}
	else if(name.compare(QString("abs"))==0)
	{
		if(oper1->get_vartype()==Integer)
		{
			c_type* temp = new c_type;
			result->set_vartype(Integer);
			temp->i = abs(oper1->get_value()->i);
			result->set_value(temp);
			return 1;
		}
		else if(oper1->get_vartype()==Real)
		{
			c_type* temp = new c_type;
			result->set_vartype(Real);
			temp->f = abs(oper1->get_value()->f);
			result->set_value(temp);
			return 0;
		}
	}
	else if(name.compare(QString("exp"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = exp(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
		
	}
	else if(name.compare(QString("sin"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = sin(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
	}
	else if(name.compare(QString("cos"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = cos(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
	}
	else if(name.compare(QString("tan"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = tan(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
	}
	else if(name.compare(QString("arctan"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = atan(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
	}
	else if(name.compare(QString("trunc"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Real);
		temp->f = trunc(oper1->get_value()->f);
		result->set_value(temp);
		return 0;
	}
	else if(name.compare(QString("round"))==0)
	{
		c_type* temp = new c_type;
		result->set_vartype(Integer);
		temp->f = floor(oper1->get_value()->f+0.5);
		result->set_value(temp);
		return 1;
	}
	else if(name.compare(QString("random"))==0)
	{
		srand(NULL);
		if(oper1!=NULL)
		{
			c_type* temp = new c_type;
			result->set_vartype(Integer);
			temp->f = rand()%oper1->get_value()->i;
			result->set_value(temp);
			return 1;
		}
		else
		{
			c_type* temp = new c_type;
			result->set_vartype(Real);
			temp->f =(rand()%100)/100.0;
			result->set_value(temp);
			return 0;			
		}
	}

}

double trunc(double d)
{ 
	return (d>0) ? floor(d) : ceil(d) ; 
}